package com.hsc.www.common;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class UserController {
    @Autowired
    private ServerProperties serverProperties;


    @RequestMapping("/getUsers")
    @HystrixCommand(fallbackMethod = "getUsersError")
    List<User> getAll() throws Exception {
        Long random = System.currentTimeMillis() % 10;

        if (random < 3) {
            throw new RuntimeException("手抛异常");
        }

        TimeUnit.SECONDS.sleep(random);

        List<User> userList = new ArrayList<>();
        for (int i = 1; i <= random; i++) {
            User user = new User();
            user.setName("张三" + i);
            user.setAge(i);
            user.setServer(serverProperties.getPort().toString());
            userList.add(user);
        }
        return userList;
    }

    List<User> getUsersError() {
        User user = new User();
        user.setName("error");
        user.setServer(serverProperties.getPort().toString());
        List<User> userList = new ArrayList<>();
        userList.add(user);
        return userList;
    }

}
